using AjaxControlToolkit;
using ASP;
using ClassLibrary.BusinessLayer.Facade;
using IPMS.AccessAuth;
using IPMS.BLL;
using Resources;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Globalization;
using System.Text;
using System.Threading;
using System.Web.Profile;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Product : Page, IRequiresSessionState
{
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        Auth canAdd = new Auth(this.Session["UserId"].ToString(), string.Empty, "Product");
        if (!canAdd.CanAdd())
        {
            this.lblError.Visible = true;
            this.lblError.Text = Messages.mNoAdd.ToString();
        }
        else
        {
            this.setButtons("Add");
            this.setText(false);
            this.clearText();
            this.txtModel.ReadOnly = false;
            this.txtRevision.ReadOnly = false;
            this.txtModel.Enabled = true;
            this.txtRevision.Enabled = true;
            this.txtModel.Focus();
        }
    }

    protected void btnAddProjectToProduct_Click(object sender, EventArgs e)
    {
        this.GenerateOpenFilter();
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        this.clearText();
        this.setText(true);
        this.setButtons(string.Empty);
    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        Auth canDelete = new Auth(this.Session["UserId"].ToString(), string.Empty, "Product");
        if (!canDelete.CanDelete())
        {
            this.lblError.Visible = true;
            this.lblError.Text = Messages.mNoDelete.ToString();
        }
        else
        {
            try
            {
                this.ODSProducts.DeleteMethod = "Delete";
                this.ODSProducts.DeleteParameters["Original_Model"].DefaultValue = this.GridViewProducts.DataKeys[this.GridViewProducts.SelectedIndex].Values["Model"].ToString();
                this.ODSProducts.Delete();
                this.clearText();
                this.Search("");
                this.setText(true);
                this.setButtons(string.Empty);
            }
            catch (Exception)
            {
                this.lblError.Visible = true;
                this.lblError.Text = Messages.DELETE_ProductInUsed.ToString();
            }
        }
    }

    protected void btnDeleteProject_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow gvRow in this.gvProjects.Rows)
        {
            CheckBox cb = (CheckBox) gvRow.FindControl("cbDelete");
            if ((cb != null) && cb.Checked)
            {
                try
                {
                    new ProductProject(this.GridViewProducts.SelectedValue.ToString(), this.gvProjects.DataKeys[gvRow.RowIndex].Values["ProjectCode"].ToString(), null, null, null).DeleteProductProject();
                }
                catch (ArgumentOutOfRangeException)
                {
                }
            }
        }
        this.gvProjects.DataBind();
        this.btnDelete.Enabled = this.gvProjects.Rows.Count != 0;
    }

    protected void btnModify_Click(object sender, EventArgs e)
    {
        Auth canUpdate = new Auth(this.Session["UserId"].ToString(), string.Empty, "Product");
        if (!canUpdate.CanUpdate())
        {
            this.lblError.Visible = true;
            this.lblError.Text = Messages.mNoEdit.ToString();
        }
        else
        {
            this.setButtons("Update");
            this.setText(false);
            this.txtModel.ReadOnly = true;
            this.txtRevision.ReadOnly = true;
            this.txtModel.Enabled = false;
            this.txtRevision.Enabled = false;
            this.txtModelName.Focus();
            this.GenerateOpenFilter();
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            if (this.cbForUpdate.Checked)
            {
                this.ODSProducts.UpdateMethod = "Update";
                this.ODSProducts.UpdateParameters["Model"].DefaultValue = this.txtModel.Text.ToString();
                this.ODSProducts.UpdateParameters["Revision"].DefaultValue = this.txtRevision.Text.ToString();
                this.ODSProducts.UpdateParameters["ModelName"].DefaultValue = this.txtModelName.Text.ToString();
                this.ODSProducts.UpdateParameters["Specification"].DefaultValue = this.txtSpecification.Text.ToString();
                this.ODSProducts.UpdateParameters["Remark1"].DefaultValue = this.txtRemarks1.Text.ToString();
                this.ODSProducts.UpdateParameters["Remark2"].DefaultValue = this.txtRemarks2.Text.ToString();
                this.ODSProducts.UpdateParameters["Remark3"].DefaultValue = this.txtRemarks3.Text.ToString();
                this.ODSProducts.UpdateParameters["Remark4"].DefaultValue = this.txtRemarks4.Text.ToString();
                this.ODSProducts.UpdateParameters["Remark5"].DefaultValue = this.txtRemarks5.Text.ToString();
                this.ODSProducts.UpdateParameters["DateFld1"].DefaultValue = IPDataFormat.ConvertDateFormat(this.txtDate1.Text.ToString(), 1);
                this.ODSProducts.UpdateParameters["DateFld2"].DefaultValue = IPDataFormat.ConvertDateFormat(this.txtDate2.Text.ToString(), 1);
                this.ODSProducts.UpdateParameters["DateFld3"].DefaultValue = IPDataFormat.ConvertDateFormat(this.txtDate3.Text.ToString(), 1);
                this.ODSProducts.UpdateParameters["DateFld4"].DefaultValue = IPDataFormat.ConvertDateFormat(this.txtDate4.Text.ToString(), 1);
                this.ODSProducts.UpdateParameters["DateFld5"].DefaultValue = IPDataFormat.ConvertDateFormat(this.txtDate5.Text.ToString(), 1);
                this.ODSProducts.UpdateParameters["DeciFld1"].DefaultValue = this.txtDeci1.Text.ToString();
                this.ODSProducts.UpdateParameters["DeciFld2"].DefaultValue = this.txtDeci2.Text.ToString();
                this.ODSProducts.UpdateParameters["UpdateBy"].DefaultValue = this.Page.User.Identity.Name.ToString();
                this.ODSProducts.UpdateParameters["CreateDate"].DefaultValue = IPDataFormat.ConvertDateFormat(this.txtCreateDate.Text.ToString(), 1);
                this.ODSProducts.UpdateParameters["Original_Model"].DefaultValue = this.txtModel.Text.ToString();
                this.ODSProducts.Update();
                this.btnCancel_Click(base.Server, e);
            }
            else
            {
                this.ODSProducts.InsertMethod = "Insert";
                this.ODSProducts.InsertParameters["Model"].DefaultValue = this.txtModel.Text.ToString();
                this.ODSProducts.InsertParameters["Revision"].DefaultValue = this.txtRevision.Text.ToString();
                this.ODSProducts.InsertParameters["ModelName"].DefaultValue = this.txtModelName.Text.ToString();
                this.ODSProducts.InsertParameters["Specification"].DefaultValue = this.txtSpecification.Text.ToString();
                this.ODSProducts.InsertParameters["Remark1"].DefaultValue = this.txtRemarks1.Text.ToString();
                this.ODSProducts.InsertParameters["Remark2"].DefaultValue = this.txtRemarks2.Text.ToString();
                this.ODSProducts.InsertParameters["Remark3"].DefaultValue = this.txtRemarks3.Text.ToString();
                this.ODSProducts.InsertParameters["Remark4"].DefaultValue = this.txtRemarks4.Text.ToString();
                this.ODSProducts.InsertParameters["Remark5"].DefaultValue = this.txtRemarks5.Text.ToString();
                this.ODSProducts.InsertParameters["DateFld1"].DefaultValue = IPDataFormat.ConvertDateFormat(this.txtDate1.Text.ToString(), 1);
                this.ODSProducts.InsertParameters["DateFld2"].DefaultValue = IPDataFormat.ConvertDateFormat(this.txtDate2.Text.ToString(), 1);
                this.ODSProducts.InsertParameters["DateFld3"].DefaultValue = IPDataFormat.ConvertDateFormat(this.txtDate3.Text.ToString(), 1);
                this.ODSProducts.InsertParameters["DateFld4"].DefaultValue = IPDataFormat.ConvertDateFormat(this.txtDate4.Text.ToString(), 1);
                this.ODSProducts.InsertParameters["DateFld5"].DefaultValue = IPDataFormat.ConvertDateFormat(this.txtDate5.Text.ToString(), 1);
                this.ODSProducts.InsertParameters["DeciFld1"].DefaultValue = this.txtDeci1.Text.ToString();
                this.ODSProducts.InsertParameters["DeciFld2"].DefaultValue = this.txtDeci2.Text.ToString();
                this.ODSProducts.InsertParameters["CreateBy"].DefaultValue = this.Page.User.Identity.Name.ToString();
                this.ODSProducts.InsertParameters["UpdateBy"].DefaultValue = this.Page.User.Identity.Name.ToString();
                this.ODSProducts.InsertParameters["OwnerGroupID"].DefaultValue = this.Session["OwnerGroupID"].ToString();
                this.ODSProducts.InsertParameters["CreateDate"].DefaultValue = IPDataFormat.ConvertDateFormat(this.txtCreateDate.Text.ToString(), 1);
                this.ODSProducts.Insert();
            }
            this.GridViewProducts.DataBind();
            this.searchGrid(this.txtModel.Text.ToString());
            this.cbForUpdate.Checked = false;
            this.setButtons(string.Empty);
            this.setText(true);
            this.clearText();
            this.Search("");
            this.SwitchTab(1);
            this.GenerateOpenFilter();
        }
        catch (Exception ex)
        {
            List<string> lstValues = new List<string>();
            //this.lblError.Text = IPDataFormat.GenerateMessage(ex, lstValues);
            this.lblError.Text = ex.Message.ToString();
            this.chkForOperation.Checked = true;
        }
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        this.Search("");
    }

    private void clearText()
    {
        this.txtModel.Text = string.Empty;
        this.txtRevision.Text = string.Empty;
        this.txtModelName.Text = string.Empty;
        this.txtSpecification.Text = string.Empty;
        this.txtCreateDate.Text = string.Empty;
        this.txtRemarks1.Text = string.Empty;
        this.txtRemarks2.Text = string.Empty;
        this.txtRemarks3.Text = string.Empty;
        this.txtRemarks4.Text = string.Empty;
        this.txtRemarks5.Text = string.Empty;
        this.txtDate1.Text = string.Empty;
        this.txtDate2.Text = string.Empty;
        this.txtDate3.Text = string.Empty;
        this.txtDate4.Text = string.Empty;
        this.txtDate5.Text = string.Empty;
        this.txtDeci1.Text = string.Empty;
        this.txtDeci2.Text = string.Empty;
        this.chkForOperation.Checked = false;
        this.lblError.Text = "";
    }

    protected void GenerateOpenFilter()
    {
        if (this.GridViewProducts.SelectedIndex != -1)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<script> function OpenFilter() {");
            sb.AppendLine("window.showModalDialog('FilterProject.aspx?Model=" + this.GridViewProducts.DataKeys[this.GridViewProducts.SelectedIndex].Values["Model"].ToString() + "'");
            sb.AppendLine(",'newwindow', 'dialogHeight:600px; dialogWidth: 850px; dialogTop: 197px; dialogLeft: 894px; edge: Raised; center: Yes; resizable: No; status: Yes');");
            sb.AppendLine("}</script>");
            this.Page.ClientScript.RegisterClientScriptBlock(this.Page.GetType(), "OpenFilter", sb.ToString());
        }
    }

    protected void GridViewProducts_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        this.GridViewProducts.PageIndex = e.NewPageIndex;
        this.GridViewProducts.DataBind();
        this.Search("");
    }

    protected void GridViewProducts_RowCreated(object sender, GridViewRowEventArgs e)
    {
        this.Sort(e, this.GridViewProducts);
    }

    protected void GridViewProducts_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.PopulateProduct(this.GridViewProducts.DataKeys[this.GridViewProducts.SelectedIndex].Values["Model"].ToString());
    }

    protected void GridViewProducts_Sorting(object sender, GridViewSortEventArgs e)
    {
        try
        {
            try
            {
                this.Search(e.SortExpression);
            }
            catch (NotSupportedException)
            {
            }
            catch (Exception)
            {
            }
        }
        finally
        {
            e.Cancel = true;
        }
    }

    protected void ibGeneral_Click(object sender, ImageClickEventArgs e)
    {
        this.SwitchTab(1);
        this.GenerateOpenFilter();
    }

    protected void ibMisc_Click(object sender, ImageClickEventArgs e)
    {
        this.SwitchTab(2);
        this.GenerateOpenFilter();
    }

    protected void ibProject_Click(object sender, ImageClickEventArgs e)
    {
        this.SwitchTab(3);
        this.GenerateOpenFilter();
    }

    protected override void InitializeCulture()
    {
        string sCulture = ConfigurationManager.AppSettings["DefaultCulture"].ToString();
        try
        {
            sCulture = this.Session["Culture"].ToString();
        }
        catch (NullReferenceException)
        {
        }
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(sCulture);
        Thread.CurrentThread.CurrentUICulture = new CultureInfo(sCulture);
        base.InitializeCulture();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ((Label)this.Master.FindControl("lblMstTitle")).Text = "| " + ISitemap.ProductManage.ToString() + " | " + ISitemap.ProductList.ToString();

        }
        Auth canView = new Auth(this.Session["UserId"].ToString(), string.Empty, "Product");
        if (!canView.CanView())
        {
            base.Response.Redirect("ErrorPage/NotAllowed.aspx");
        }
        else
        {
            this.lblError.Visible = false;
            try
            {
                if (!this.Page.IsPostBack)
                {
                    this.setButtons(string.Empty);
                    this.setText(true);
                    this.SwitchTab(1);
                    this.btnDelete.Attributes.Add("onClick", "return confirm('" + Messages.DeleteConfirmation.ToString() + "')");
                    this.btnDeleteProject.Attributes.Add("onClick", "return confirm('" + Messages.DeleteConfirmation.ToString() + "')");
                }
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("<script>");
                sb.AppendLine("function Reset() {");
                sb.AppendLine(" document.getElementById('" + this.txtSearchCreateDate.ClientID.ToString() + "').value = '';");
                sb.AppendLine("document.getElementById('" + this.txtSearchModel.ClientID.ToString() + "').value = '';");
                sb.AppendLine("document.getElementById('" + this.txtSearchSpecs.ClientID.ToString() + "').value = '';");
                sb.AppendLine("document.getElementById('" + this.txtSearchModelName.ClientID.ToString() + "').value = '';");
                sb.AppendLine("}</script>");
                this.Page.ClientScript.RegisterClientScriptBlock(this.Page.GetType(), "OpenPrint", sb.ToString());
            }
            catch (NullReferenceException)
            {
            }
        }
    }

    protected void PopulateProduct(string Model)
    {
        this.chkForOperation.Checked = true;
        this.cbForUpdate.Checked = true;
        ProductsClass runMethod = new ProductsClass();
        runMethod.GetProductInfo(Model);
        this.txtModel.Text = Model;
        this.txtRevision.Text = runMethod.Revision;
        this.txtModelName.Text = runMethod.ModelName;
        this.txtSpecification.Text = runMethod.Specification;
        this.txtCreateDate.Text = IPDataFormat.FormatDateTime(runMethod.CreateDate);
        this.txtRemarks1.Text = runMethod.Remark1;
        this.txtRemarks2.Text = runMethod.Remark2;
        this.txtRemarks3.Text = runMethod.Remark3;
        this.txtRemarks4.Text = runMethod.Remark4;
        this.txtRemarks5.Text = runMethod.Remark5;
        this.txtDate1.Text = IPDataFormat.FormatDateTime(runMethod.DateFld1);
        this.txtDate2.Text = IPDataFormat.FormatDateTime(runMethod.DateFld2);
        this.txtDate3.Text = IPDataFormat.FormatDateTime(runMethod.DateFld3);
        this.txtDate4.Text = IPDataFormat.FormatDateTime(runMethod.DateFld4);
        this.txtDate5.Text = IPDataFormat.FormatDateTime(runMethod.DateFld5);
        this.txtDeci1.Text = string.Format("{0:#,##0.00}", Convert.ToDecimal(runMethod.DeciFld1));
        this.txtDeci2.Text = string.Format("{0:#,##0.00}", Convert.ToDecimal(runMethod.DeciFld2));
        this.GenerateOpenFilter();
        this.setButtons(string.Empty);
        this.gvProjects.DataBind();
    }

    protected void Search(string SortExpression)
    {
        ProductFacade facade = new ProductFacade();
        SqlParameter[] sqlparam = new SqlParameter[4];
        sqlparam[0] = new SqlParameter();
        sqlparam[0].ParameterName = "@Model";
        sqlparam[0].Value = this.txtSearchModel.Text.ToString();
        sqlparam[1] = new SqlParameter();
        sqlparam[1].ParameterName = "@ModelName";
        sqlparam[1].Value = this.txtSearchModelName.Text.ToString();
        sqlparam[2] = new SqlParameter();
        sqlparam[2].ParameterName = "@CreateDate";
        sqlparam[2].Value = IPDataFormat.ConvertDateFormat(this.txtSearchCreateDate.Text.ToString(), 1);
        sqlparam[3] = new SqlParameter();
        sqlparam[3].ParameterName = "@Specification";
        sqlparam[3].Value = this.txtSearchSpecs.Text.ToString();
        DbParameter[] param = sqlparam;
        DataView dv = facade.GetsProduct("_IPMS_ProductSearch_SP", param).DefaultView;
        dv.Sort = SortExpression;
        this.GridViewProducts.DataSourceID = string.Empty;
        this.GridViewProducts.DataSource = dv;
        this.GridViewProducts.DataBind();
    }

    private void searchGrid(string Val)
    {
        foreach (GridViewRow gvRow in this.GridViewProducts.Rows)
        {
            if (Val == this.GridViewProducts.DataKeys[gvRow.RowIndex].Value.ToString())
            {
                this.GridViewProducts.SelectedIndex = gvRow.RowIndex;
            }
        }
    }

    private void setButtons(string action)
    {
        string strname0 = action;
        if (strname0 != null)
        {
            if (!(strname0 == "Add"))
            {
                if (strname0 == "Update")
                {
                    this.btnAdd.Enabled = false;
                    this.btnModify.Enabled = false;
                    this.btnDelete.Enabled = false;
                    this.btnSave.Enabled = true;
                    goto Label_013D;
                }
                if (strname0 == "Save")
                {
                    this.btnAdd.Enabled = true;
                    this.btnModify.Enabled = true;
                    this.btnDelete.Enabled = true;
                    this.btnSave.Enabled = false;
                    goto Label_013D;
                }
            }
            else
            {
                this.btnAdd.Enabled = false;
                this.btnModify.Enabled = false;
                this.btnDelete.Enabled = false;
                this.btnSave.Enabled = true;
                goto Label_013D;
            }
        }
        this.btnAdd.Enabled = true;
        this.btnModify.Enabled = this.txtModel.Text.Length != 0;
        this.btnSave.Enabled = false;
        this.btnDelete.Enabled = this.txtModel.Text.Length != 0;
    Label_013D:
        if ((this.txtModel.Text.Length != 0) & this.txtModel.ReadOnly)
        {
            this.btnAddProjectToProduct.Enabled = true;
        }
        else
        {
            this.btnAddProjectToProduct.Enabled = false;
        }
    }

    private void setText(bool bBool)
    {
        this.txtModel.ReadOnly = bBool;
        this.txtRevision.ReadOnly = bBool;
        this.txtModelName.ReadOnly = bBool;
        this.txtSpecification.ReadOnly = bBool;
        this.txtCreateDate.Enabled = !bBool;
        this.txtRemarks1.ReadOnly = bBool;
        this.txtRemarks2.ReadOnly = bBool;
        this.txtRemarks3.ReadOnly = bBool;
        this.txtRemarks4.ReadOnly = bBool;
        this.txtRemarks5.ReadOnly = bBool;
        this.txtDate1.Enabled = !bBool;
        this.txtDate2.Enabled = !bBool;
        this.txtDate3.Enabled = !bBool;
        this.txtDate4.Enabled = !bBool;
        this.txtDate5.Enabled = !bBool;
        this.txtDeci1.ReadOnly = bBool;
        this.txtDeci2.ReadOnly = bBool;
    }

    protected void Sort(GridViewRowEventArgs e, GridView gv)
    {
        if ((e.Row != null) && (e.Row.RowType == DataControlRowType.Header))
        {
            foreach (TableCell cell in e.Row.Cells)
            {
                if (cell.HasControls())
                {
                    LinkButton button = (LinkButton) cell.Controls[0];
                    if (button != null)
                    {
                        Image image = new Image();
                        image.ImageUrl = "";
                        if (gv.SortExpression == button.CommandArgument)
                        {
                            if (gv.SortDirection == SortDirection.Ascending)
                            {
                                image.ImageUrl = "images/sortup.gif";
                            }
                            else
                            {
                                image.ImageUrl = "images/sortdown.gif";
                            }
                        }
                        if (image.ImageUrl != "")
                        {
                            cell.Controls.Add(image);
                        }
                    }
                }
            }
        }
    }

    protected void SwitchTab(int Tab)
    {
        string culture = this.Session["Culture"].ToString().ToLower();
        switch (Tab)
        {
            case 1:
                this.PanelGeneral.Visible = true;
                this.PanelMisc.Visible = false;
                this.PanelProject.Visible = false;
                this.PanelButton.Visible = true;
                this.ibGeneral.ImageUrl = "~/Images/a_General_blue-" + culture + ".gif";
                this.ibMisc.ImageUrl = "~/Images/a_Others_gray-" + culture + ".gif";
                this.ibProject.ImageUrl = "~/Images/a_ProjectList_gray-" + culture + ".gif";
                break;

            case 2:
                this.PanelGeneral.Visible = false;
                this.PanelMisc.Visible = true;
                this.PanelProject.Visible = false;
                this.PanelButton.Visible = true;
                this.ibGeneral.ImageUrl = "~/Images/a_General_gray-" + culture + ".gif";
                this.ibMisc.ImageUrl = "~/Images/a_Others_blue-" + culture + ".gif";
                this.ibProject.ImageUrl = "~/Images/a_ProjectList_gray-" + culture + ".gif";
                break;

            case 3:
                this.PanelGeneral.Visible = false;
                this.PanelMisc.Visible = false;
                this.PanelProject.Visible = true;
                this.PanelButton.Visible = false;
                this.ibGeneral.ImageUrl = "~/Images/a_General_gray-" + culture + ".gif";
                this.ibMisc.ImageUrl = "~/Images/a_Others_gray-" + culture + ".gif";
                this.ibProject.ImageUrl = "~/Images/a_ProjectList_blue-" + culture + ".gif";
                this.gvProjects.DataBind();
                break;
        }
    }
    protected void btnNewProduct_Click(object sender, EventArgs e)
    {
        base.Response.Redirect("ProductAdd.aspx");
    }
}
